Inheritence

Inheritance

Inheritance allows one class (child class) to inherit the properties and methods of another class (parent class). It supports reusability and method overriding.

Types of Inheritance


// Example of Single Inheritance
class Animal {
    void eat() {
        System.out.println("This animal eats food");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("Dog barks");
    }
}

Super Keyword

The 'super' keyword refers to the immediate parent class. It is used to access parent class methods, constructors, and variables.


class Parent {
    void display() {
        System.out.println("Parent class method");
    }
}

class Child extends Parent {
    void display() {
        super.display(); // Calls parent class method
        System.out.println("Child class method");
    }
}

Method Overriding

Method overriding occurs when a child class provides its own implementation of a method already defined in its parent class.


class Vehicle {
    void run() {
        System.out.println("Vehicle is running");
    }
}

class Bike extends Vehicle {
    void run() {
        System.out.println("Bike is running safely");
    }
}

Covariant Return Type

In method overriding, a child class can return a subtype of the parent class's return type. This is called a covariant return type.


class Parent {
    Parent get() {
        return this;
    }
}

class Child extends Parent {
    @Override
    Child get() {  // Covariant return type
        return this;
    }
}

Abstract Class

An abstract class cannot be instantiated directly. It can have abstract methods (methods without a body) and concrete methods.


abstract class Shape {
    abstract void draw(); // Abstract method (no body)

    void message() {
        System.out.println("This is a shape");
    }
}

class Circle extends Shape {
    void draw() {
        System.out.println("Drawing a circle");
    }
}

Viva/Interview Questions (Inheritance & Related Concepts)

Inheritance is a mechanism in Java where one class inherits the properties and methods of another class.
The 'super' keyword is used to access the parent class’s constructor, methods, or variables.
Method overriding occurs when a child class redefines a method with the same signature as one in the parent class.
A covariant return type allows the overridden method in the child class to return a subtype of the return type declared in the parent class.
An abstract class cannot be instantiated directly and may contain abstract methods (without implementation).
Abstract classes are incomplete, so they require a child class to implement their abstract methods.